package com.example.demo.config;

import com.example.demo.common.Func;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
@Slf4j
public class AsyncConfig implements AsyncConfigurer {

    @Override
    @Bean(name = "sendEmailAsync")
    public AsyncTaskExecutor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // 核心线程数：线程池创建的时候初始化的线程数（设置为CPU核心数）
        int corePoolSize = Runtime.getRuntime().availableProcessors();
        executor.setCorePoolSize(corePoolSize);
        Func.print("corePoolSize:" + corePoolSize);

        // 最大线程数：线程池最大的线程数，只有缓冲队列满了之后才会申请超过核心线程数的线程
        // 设置为核心数的两倍
        int maxPoolSize = corePoolSize * 2;
        executor.setMaxPoolSize(maxPoolSize);
        Func.print("maxPoolSize:" + maxPoolSize);

        // 缓冲队列：用来缓冲执行任务的队列
        executor.setQueueCapacity(50);

        // 线程池关闭：等待所有任务都完成再关闭
        executor.setWaitForTasksToCompleteOnShutdown(true);

        // 线程等待时间：关闭时最多等待60秒后强制停止
        executor.setAwaitTerminationSeconds(60);

        // 线程空闲时间：超过核心线程之外的线程到达60秒后会被销毁
        executor.setKeepAliveSeconds(60);

        // 线程名称前缀（被执行的线程的名称前缀）
        executor.setThreadNamePrefix("ly-Async-");

        // 线程池对拒绝任务(无线程可用)的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 设置拒绝策略：当工作队列已满，线程数为最大线程数的时候，接收新任务抛出RejectedExecutionException异常
        //executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());

        // 初始化线程
        executor.initialize();

        return executor;
    }

    /*@Bean(name = "sendEmailScheduler")
    public TaskScheduler getTaskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(10);
        scheduler.setThreadNamePrefix("my-scheduler-");
        scheduler.initialize();
        return scheduler;
    }*/

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (throwable, method, objects) -> {
            //可以做一些其他的业务处理，比如：异常记录日志
            log.error("class: {}", method.getDeclaringClass().getName());
            log.error("method：{}", method.getName());
            log.error("type：{}", throwable.getClass().getName());
            log.error("exception：{}", throwable.getMessage());
        };
    }

}
